package com.tarry.util;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.tarry.exception.ParamException;
import org.apache.commons.collections.MapUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.*;

/**
 *参数校验类
 */
public class BeanValidator {

    //构建Validator工厂
    private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    /**
     * 单个类数据验证
     * @param t
     * @param groups
     * @param <T>
     * @return
     */
    public static <T>Map validate(T t,Class... groups){
        Validator validator = validatorFactory.getValidator();
        Set validateResult = validator.validate(t,groups);
        if( !validateResult.isEmpty()){
            LinkedHashMap errors = Maps.newLinkedHashMap();
            Iterator iterator = validateResult.iterator();
            while ( iterator.hasNext()){
                ConstraintViolation validation =
                        (ConstraintViolation) iterator.next();
                errors.put( validation.getPropertyPath().toString(),
                        validation.getMessage());
            }
            return errors;
        }
        return Collections.emptyMap();
    }

    /**
     * Lists数据验证
     * @param collections
     * @return
     */
    public static Map validateList( Collection<?> collections){
        Preconditions.checkNotNull(collections);
        Iterator iterator = collections.iterator();
        Map errors;
        do {
            if( !iterator.hasNext() ){
                return Collections.emptyMap();
            }
            Object object = iterator.next();
            errors = validate(object,new Class[0]);
        }while (errors.isEmpty());
        return errors;
    }

    /**
     *
     * @param first
     * @param objects
     * @return
     */
    public static Map validateObject(Object first, Object... objects){
        if( objects != null && objects.length >0){
            return validateList(Lists.asList(first,objects));
        }else {
            return validate(first,new Class[0]);
        }
    }

    public static void check(Object param) throws ParamException {
        Map map = BeanValidator.validateObject(param);
        if(MapUtils.isNotEmpty(map)){
            throw new ParamException(map.toString());
        }
    }
}
